package com.luoran.car.controller;


import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Component
@ServerEndpoint("/websocket")
public class ManagementWebsocket {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connection opened: " + session.getId());
        sessions.add(session);

    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        System.out.println("接收到的消息: " + message);
        session.getBasicRemote().sendText("发送的消息: " + message);
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("Connection closed: " + session.getId());
        sessions.remove(session);
    }

    public static void  sendMessage(String message) throws IOException, EncodeException {
        for (Session session : sessions) {
            session.getBasicRemote().sendText(message);
        }
    }

    private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());

}
